/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package term_project;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
 *
 * @author Ross
 */
public class ChatPanel extends JPanel
{
    private JLabel userLabel;                                                   // Label for the user list
    private JLabel messageLabel;                                                // Label for the chat messages
    
    private JTextPane chat;                                                     // Chat list
    private StyledDocument chatText;                                            // Styled chat MesssageI
    
    private JPanel usersPanel;                                                  // Panel to hold the options for a user
    private JList usersList;                                                    // Active users in the chat
    private JScrollPane scrollUsersList;                                        // Scroll pane for the userlist
    private DefaultListModel usersModel;                                        // Active user model
    private JButton addFriend;                                                  // Add friend button
    
    private JTextArea message;                                                  // Message input
    private JScrollPane messageScroll;                                          // Message Scroll Pane
    private JButton sendMessage;                                                // Button to send the message
    private JButton whisperButton;                                              // Sends a "whisper," private message, to a user
    private JButton addUserButton;                                              // Add a user to the chat
    private JButton addFriendButton;                                            // Add friend button
    private GridBagLayout layout;                                               // Layout
    private GridLayout gLayout;
    private GridBagConstraints c;                                               // Constraints for the layout
    
    private ChatWindow parentWindow;                                            // Tracks the parent window.
    
    protected ArrayList<User> users;                                            // The current users in the chat
    protected ArrayList<Message> messageList;                                   // Holds the displayed message
    protected ArrayList<User> friends;                                          // Holds the users friends list
    private ComputerUser user;                                                  // The logged in user
    protected Chat chatObject;                                                  // Chat object
    
    public ChatPanel(ComputerUser User, Chat ChatObject, ChatWindow parentwindow)
    {
        parentWindow = parentwindow;
        user = User;
        messageList = new ArrayList();
        chatObject = new Chat(1, "Test Name");
        chatObject = ChatObject;
        
        initComponents();
        fillLists();
    }
    
    public void initComponents()
    {
        Dimension buttonDi;
        buttonDi = new Dimension(40,40);
        // ********************************
        // * Setting up the labels        *
        // ********************************
        userLabel = new JLabel("Current Users");
        messageLabel = new JLabel("Message Label");
        // *********************************
        // * Setting up the message list   *
        // *********************************
        chat = new JTextPane();
        chat.setText("");
        chat.setEditable(false);
        chatText = chat.getStyledDocument();
        // TODO: 
        //       - Add a scrollpane
       
        
        // ********************************
        // * Setting up the user list     *
        // ********************************
        usersModel = new DefaultListModel();                                    // Instantiates the default model for  the usersList
        usersList = new JList(usersModel);                                      // Creates the userlist with usersModel as the default model
        usersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);        // Only gives the user the option to select one user at a time.
        usersList.setLayoutOrientation(JList.VERTICAL);                    // Creates the vertical wrap
        usersList.setVisibleRowCount(-1);                                       // Still, no idea
        // TODO:
        //       - Add a scrollpane
                                             
        message = new JTextArea(5, 10);
        message.addKeyListener(new KeyListener(){
                                                 @Override
                                                 public void keyTyped(KeyEvent e)
                                                    {

                                                    }
                                                 @Override
                                                  public void keyPressed(KeyEvent e)
                                                  {
                                                      
                                                  }
                                                 @Override
                                                  public void keyReleased(KeyEvent e)
                                                  {
                                                        if(e.getKeyCode() == KeyEvent.VK_ENTER && !e.isShiftDown())
                                                        {
                                                            messageSendPressed();
                                                        }
                                                        else if (e.getKeyCode() == KeyEvent.VK_ENTER && e.isShiftDown())
                                                        {
                                                            message.append("\n");
                                                        }
                                                  }
                                                    });
    
        messageScroll = new JScrollPane(message);
        
        usersPanel = new JPanel();
        whisperButton = new JButton();
        whisperButton.setToolTipText("Send a whisper to user");
        whisperButton.setMinimumSize(buttonDi);
        whisperButton.setMaximumSize(buttonDi);
        whisperButton.setPreferredSize(buttonDi);
        whisperButton.addActionListener(new ActionListener() 
                                                            {
                                                               @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   whisperPressed();
                                                               }
                                                            });
        addUserButton = new JButton();
        addUserButton.setToolTipText("Add user to chat");
        addUserButton.setMinimumSize(buttonDi);
        addUserButton.setMaximumSize(buttonDi);
        addUserButton.setPreferredSize(buttonDi);
        addUserButton.addActionListener(new ActionListener() 
                                                            {
                                                               @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   addUserPressed();
                                                               }
                                                            });
        sendMessage = new JButton();
        sendMessage.setToolTipText("Send message to chat");
        sendMessage.setMinimumSize(buttonDi);
        sendMessage.setMaximumSize(buttonDi);
        sendMessage.setPreferredSize(buttonDi);
        sendMessage.addActionListener(new ActionListener() 
                                                            {
                                                                @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   messageSendPressed();
                                                               }
                                                            });
        addFriendButton = new JButton();
        addFriendButton.setToolTipText("Add selected user as friend");
        addFriendButton.setMinimumSize(buttonDi);
        addFriendButton.setMaximumSize(buttonDi);
        addFriendButton.setPreferredSize(buttonDi);
        addFriendButton.addActionListener(new ActionListener() 
                                                            {
                                                                @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   addFriendPressed();
                                                               }
                                                            });
       try
       {
        Image img = ImageIO.read(this.getClass().getResource("send.png"));
        sendMessage.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("whisper.png"));
        whisperButton.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("add.png"));
        addUserButton.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("addFriend.png"));
        addFriendButton.setIcon(new ImageIcon(img));
        
       }
       catch(IOException e)
       {
           JOptionPane.showMessageDialog(this, "Could not load buttons", "ERROR!", JOptionPane.ERROR_MESSAGE);
       }
        c = new GridBagConstraints();
        layout = new GridBagLayout();
        gLayout = new GridLayout(2,1,5,5);
        setLayout(layout);
        
        
        
        chat.setMinimumSize(new Dimension(200, 100));
        chat.setPreferredSize(new Dimension(200, 100));
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = .75;
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.anchor = GridBagConstraints.FIRST_LINE_START;
        
        add(chat, c);
        
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.weightx = .75;
        c.weighty = .4;
        c.insets = new Insets(10,0,0,0);
        add(messageScroll, c);
        
        
        c.gridx = 2;
        c.gridy = 1;
        c.weightx = .4;
        c.weighty = 0;
        c.gridwidth = 1;
        c.insets = new Insets(0,10,0,0);
        c.fill = GridBagConstraints.NONE;
        
        usersPanel.add(sendMessage);
        usersPanel.add(whisperButton);
        usersPanel.add(addUserButton);
        usersPanel.add(addFriendButton);
        
        this.add(usersPanel, c);
        c.insets = new Insets(0,10,0,0);
        c.gridx = 2;
        c.gridy = 0;
        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.BOTH;
        scrollUsersList = new JScrollPane(usersList);
        add(scrollUsersList, c);
        chatObject.sendMessage(((User)user), "Test");
        addMessage(user, "Test");
}
    
    private void fillLists()
    {
        clearLists();
        for(User uses : chatObject.getMembers())
        {
            usersModel.addElement(uses.getUsername());
        }
    }
    private void clearLists()
    {
        usersModel.clear();
    }
    public void displayMessages()
    {
        for(Message msg : chatObject.getMessages())
        {
            addMessage(msg.getUserSender(), msg.getMessage());
        }
    }
    
    public String getTitle()
    {
        return chatObject.getUsername();
    }
    
    // *************************************
    // * Action Listener Handler functins  *
    // *************************************
    private void messageSendPressed()
    {
        if(!message.getText().equals(""))
        {
            chatObject.sendMessage(user, message.getText());
            addMessage(user, message.getText());
            message.setText("");
        }
    }
    
    private void addMessage(User sender, String sentMessage)
    {
        try
        {
            SimpleAttributeSet keyword = new SimpleAttributeSet();
            StyleConstants.setBold(keyword, true);
            chatText.insertString(chatText.getLength(), "\n" +sender.getUsername() +": ", keyword);
            chatText.insertString(chatText.getLength(), sentMessage, null);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(this, "Adding message error", "ERROR!", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    private void whisperPressed()
    {
        Chat newChat;                                                           // Temporary chat object
        String answer;                                                          // The users input from the dialog box
        User friend;                                                            // Friend to add to the whisper
        answer = (String)JOptionPane.showInputDialog(this,"Input whisper title", "Chat Title", JOptionPane.OK_CANCEL_OPTION);
        if(answer != null && usersList.getSelectedIndex() != 1)
        {
            friend = chatObject.getUser(usersList.getSelectedIndex());          // Gets the user from the chat list
            System.out.println(friend.username);                                // Error checking
            if(friend != null)      
            {
                newChat = Chat.newChat(answer);                                 // Creates the private chat
                newChat.clearUsers();                                           // clears the fake users
                newChat.addUser(user);                                          // Adds logged in user
                newChat.addUser(friend);                                        // Adds the desired person to chat with
                user.addChat(newChat);                                          // Adds the chat to the tabbed panel
                parentWindow.addChat(newChat);                                  // Users the add chat function from the parent
                parentWindow.reloadParent();                                    // Refreshes all the lists
            }
        }
    }
    private void addUserPressed()
    {
        
        User newUser;
        String username;
        username = (String)JOptionPane.showInputDialog(this,"Input the users name", "Username", JOptionPane.OK_CANCEL_OPTION);
        if(username != null)
        {
            System.out.println(user.getUsername());
            System.out.println(username);
            if(user.getUsername().toLowerCase().compareTo(username.toLowerCase()) == 0)
            {
                JOptionPane.showMessageDialog(this, "User is already in the chat", "Error!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for(User selectedUser : chatObject.getMembers())
            {
                if(selectedUser.getUsername().toLowerCase().compareTo(username.toLowerCase()) == 0)
                {
                    JOptionPane.showMessageDialog(this, "User is already in the chat", "Error!", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            newUser = new User(username);
            chatObject.addUser(newUser);
            fillLists();
        }
    }
    private void addFriendPressed()
    {
        User newFriend;
        if(usersList.getSelectedIndex() == -1)
        {
            
            
        }
        else
        {
            newFriend = chatObject.getUser(usersList.getSelectedIndex());
            if(user.getFriend(newFriend.getUsername()) == null)
            {
                user.addFriend(newFriend);
                parentWindow.reloadParent();
            }
            else
            {
                JOptionPane.showMessageDialog(this, "This user is already on your friends list", "ERROR!", JOptionPane.ERROR_MESSAGE);
            }


        }
    }

}


